/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package trivia.gui;

import javax.microedition.lcdui.*;

import trivia.Subject;
import trivia.Problem;
import trivia.TriviaMIDlet;

/**
 *
 * @author mourawi
 */
public class PracticeController implements CommandListener {

    private Subject subject;

    private int problemIndex;
    
    private TriviaMIDlet midLet;

    private ProblemForm problemForm;

    private HintForm hintForm;


    public PracticeController(TriviaMIDlet midLet) {
        this.midLet = midLet;

        problemForm = new ProblemForm();
        problemForm.setCommandListener(this);

        hintForm = new HintForm();
        hintForm.setCommandListener(this);
    }


    public void start(Subject subject) {
        this.subject = subject;
        problemIndex = 0;

        problemForm.setSubject(subject);
        problemForm.displayProblem(problemIndex,subject.getProblem(problemIndex));
        midLet.switchDisplayable(null,problemForm);
    }

    
    public void commandAction(Command command, Displayable displayable) {
        if(displayable == problemForm) {
            if(command.getCommandType() == Command.OK) {
                Problem problem = subject.getProblem(problemIndex);
                if(problem.getCorrect() == problemForm.getUserAnswer()) {
                    problemIndex++;
                    if(problemIndex<subject.getProblemsNumber()) {
                        problemForm.displayProblem(problemIndex,subject.getProblem(problemIndex));
                    } else {
                        midLet.startOver();
                    }
                } else {
                    hintForm.displayHint(problem);
                    midLet.switchDisplayable(null,hintForm);
                }
            } else if(command.getCommandType() == Command.CANCEL) {
                midLet.startOver();
            }
        } else if(displayable == hintForm) {
            midLet.switchDisplayable(null,problemForm);
        }
    }

}
